package com.app.service.qzj;

import com.alibaba.fastjson.JSON;
import com.app.domain.qzj.DeviceResult;
import com.app.domain.qzj.ResultJson;
import com.app.utils.HttpRequestUtil;
import com.app.utils.SignUtils;
import com.app.utils.StringUtil;
import com.app.utils.TimeHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

@Service
@Slf4j
public class QzjService {

    public ResultJson upload(String serviceHost, String appid, String appsecret, String format, String method, String version, String data) {
        ResultJson resultJson = new ResultJson();
        resultJson.setCode(9999);
        // 如果 setMsg 是必要的，保留这行代码
        // resultJson.setMsg("系统异常");

        SignUtils.RequestInfo requestInfo = new SignUtils.RequestInfo();
        requestInfo.setAppid(appid);
        requestInfo.setAppSecret(appsecret);
        requestInfo.setFormat(format);
        requestInfo.setMethod(method);
        requestInfo.setVersion(version);
        requestInfo.setNonce(UUID.randomUUID().toString().replace("-", ""));
        requestInfo.setTimestamp(TimeHelper.getCurrentCompactTime());

        try {
            data = URLEncoder.encode(data, StandardCharsets.UTF_8.toString());
            requestInfo.setData(data);
        } catch (UnsupportedEncodingException e) {
            log.error("系统异常: 不支持的编码", e);
            resultJson.setMsg("URLEncode异常: 不支持的编码");
            return resultJson;
        }

        String sign = null;
        try {
            sign = SignUtils.buildSign(requestInfo);
            log.info("生成的签名: {}", sign);
        } catch (NoSuchAlgorithmException e) {
            log.error("系统异常", e);
            resultJson.setMsg("sign生成异常");
            return resultJson;
        } catch (UnsupportedEncodingException e) {
            log.error("系统异常", e);
            resultJson.setMsg("sign生成异常");
            return resultJson;
        }

        Map<String, String> request = new HashMap<>();
        request.put("appid", appid);
        request.put("format", format);
        request.put("method", method);
        request.put("nonce", requestInfo.getNonce());
        request.put("timestamp", requestInfo.getTimestamp());
        request.put("version", version);
        request.put("data", requestInfo.getData());
        request.put("sign", sign);

        DeviceResult responseResult = null;
        try {
            String result = HttpRequestUtil.post(request, serviceHost, new HashMap<String, String>(), "application/x-www-form-urlencoded");
            log.info("上传信息: {}", result);
            if (StringUtils.isNotBlank(result)) {
                responseResult = (DeviceResult) JSON.parseObject(StringUtil.replaceBlank(result), DeviceResult.class);
            } else {
                log.error("响应结果为空");
                resultJson.setMsg("响应结果为空");
                return resultJson;
            }
        } catch (IOException e) {
            log.error("网络连接异常", e);
            resultJson.setMsg("网络连接异常");
            return resultJson;
        } catch (TimeoutException e) {
            log.error("请求超时", e);
            resultJson.setMsg("请求超时");
            return resultJson;
        } catch (Exception e) {
            log.error("系统异常", e);
            resultJson.setMsg("上传失败");
            return resultJson;
        }

        if (responseResult != null) {
            if (responseResult.isSuccess() && "0".equals(responseResult.getCode()) && "调用成功".equals(responseResult.getMessage())) {
                resultJson.setCode(0);
                resultJson.setMsg("上传成功");
            } else {
                resultJson.setMsg(responseResult.getMessage());
            }
        } else {
            resultJson.setMsg("上传失败");
        }

        return resultJson;
    }
}
